package com.whmskj.xjlhsc.qianYiData.controller;

import com.whmskj.xjlhsc.qianYiData.service.AMonthlyAverageTonOfGauzeConsumpService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/qianYiData/aMonthlyAvg")
@RequiredArgsConstructor
public class AMonthlyAverageTonOfGauzeConsumpController {

    private final AMonthlyAverageTonOfGauzeConsumpService service;

    // 手动触发（POST/GET 皆可）：/qianYiData/aMonthlyAvg/sync?day=2025-09-07
    @PostMapping("/sync")
    public Map<String, Object> syncPost(@RequestParam String day) {
        return doSync(day);
    }

    @GetMapping("/sync")
    public Map<String, Object> syncGet(@RequestParam String day) {
        return doSync(day);
    }

    private Map<String, Object> doSync(String day) {
        LocalDate d = LocalDate.parse(day);
        
        // 第一次尝试
        int affected = service.syncForDay(d);
        
        // 如果第一次没有插入数据，等待1秒后重试一次
        if (affected == 0) {
            try {
                Thread.sleep(1000); // 等待1秒
                affected = service.syncForDay(d);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        Map<String, Object> resp = new HashMap<>();
        resp.put("day", day);
        resp.put("affected", affected);
        resp.put("retry", affected == 0 ? "failed" : "success");
        return resp;
    }
}

